from app.db import db
from app.models.SoapOperaModel import SoapOperaModel
from app.decorators.checkMissingArgs import checkMissingArgs
from sqlalchemy import and_, or_
from .utils.buildFilters import build_filters


class SoapOperaService:
    @checkMissingArgs(['title', 'description', 'type', 'director', 'year', 'rating', 'cover', 'episodes'])
    def create_soap_opera(self, title, description, type, director, year, rating, cover, episodes):
        try:
            soap_opera = SoapOperaModel(title=title, description=description, type=type, director=director, year=year, rating=rating, cover=cover, episodes=episodes)
            db.session.add(soap_opera)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            raise e
        pass

    @checkMissingArgs(['title', 'description', 'type', 'director', 'year', 'rating', 'cover', 'episodes'])
    def update_soap_opera(self, id, title, description, type, director, year, rating, cover, episodes):
        try:
            soap_opera = SoapOperaModel.query.get(id)
            if soap_opera:
                soap_opera.title = title
                soap_opera.description = description
                soap_opera.type = type
                soap_opera.director = director
                soap_opera.year = year
                soap_opera.rating = rating
                soap_opera.cover = cover
                soap_opera.episodes = episodes
                db.session.commit()
        except Exception as e:
            db.session.rollback()

    @checkMissingArgs()
    def get_soap_opera_by_id(self, id):
        return SoapOperaModel.query.get(id)

    def get_soap_opera_list(self, page_num, page_size, title, type, director, year, rating):

        try:
            filters = build_filters(model=SoapOperaModel, title=title, type=type, director=director, year=year, rating=rating,fuzzy_fields=['title', "director" ])
            soap_opera_list = SoapOperaModel.query.filter(and_(*filters)).paginate(page=page_num, per_page=page_size)
        
            return soap_opera_list
        except Exception as e:
            raise e
        
    def get_soap_opera_total(self, title, type, director, year, rating):
        try:
            filters = build_filters(model=SoapOperaModel, title=title, type=type, director=director, year=year, rating=rating, fuzzy_fields=['title', "director" ])
            total = SoapOperaModel.query.filter(and_(*filters)).count()
            return total
        except Exception as e:
            raise e

    @checkMissingArgs()
    def delete_soap_opera(self, ids: list):
        try:
            SoapOperaModel.query.filter(SoapOperaModel.id.in_(ids)).delete(synchronize_session=False)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            raise e
        pass